package com;

import com.entity.Department;
import com.entity.Post;
import com.entity.Staff;
import com.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author Simon
 */
public class Test {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();

        System.out.println("查询ID为1的职员数据");
        Staff staff = session.get(Staff.class, 1);
        System.out.println(staff);

        System.out.println("通过职员得到中间表staff_post数据");
        for (Post post : staff.getPostSet()) {
            System.out.println(post);
        }

        System.out.println("清除职员中间表staff_post的数据");
        staff.getPostSet().clear();

        System.out.println("查询ID为2的职位数据");
        Post post = session.get(Post.class, 2);
        System.out.println(post);

        System.out.println("将查到的职位给职员新增中间表staff_post数据");
        staff.getPostSet().add(post);

        System.out.println("查询ID为1的职员数据");
        staff = session.get(Staff.class, 1);
        System.out.println(staff);

        System.out.println("通过职员得到中间表staff_post数据");
        for (Post temp : staff.getPostSet()) {
            System.out.println(temp);
        }

        System.out.println("通过职员得到部门表department数据");
        System.out.println(staff.getDepartmentId());

        System.out.println("查询ID为1的部门数据");
        Department department = session.get(Department.class, 1);
        System.out.println(department);

        System.out.println("将查到的部门department给职员emp利用脏检查修改");
        staff.setDepartmentId(department);

        System.out.println("查询ID为1的职员数据");
        staff = session.get(Staff.class, 1);
        System.out.println(staff);

        System.out.println("通过职员得到部门表department数据");
        System.out.println(staff.getDepartmentId());

        System.out.println("查询ID为2的部门数据");
        department = session.get(Department.class, 2);
        System.out.println(department);

        System.out.println("得到部门对象所属职员");
        for (Staff s : department.getStaffSet()) {
            System.out.println(s);
        }

        System.out.println("利用脏检查删除部门对象所属的ID为1的职员");
        department.getStaffSet().remove(staff);

        System.out.println("重新查询ID为2的部门数据");
        department = session.get(Department.class, 2);
        System.out.println(department);

        System.out.println("得到部门对象所属职员");
        for (Staff s : department.getStaffSet()) {
            System.out.println(s);
        }

        //不提交,则上面的结果不会对数据库执行操作
//        transaction.commit();
    }
}
